package com.gitee.wsl.doc.prosemirror.model.content.ext

import com.gitee.wsl.doc.prosemirror.model.content.ResolvedPos
import com.gitee.wsl.doc.prosemirror.model.content.ResolvedPosRange
import kotlin.math.min


// Returns an array of all depths for which _from - _to spans the whole content of the nodes at that depth.
@Suppress("ComplexCondition")
fun coveredDepths(_from: ResolvedPos, _to: ResolvedPos): List<Int> {
    val result = mutableListOf<Int>()
    val minDepth = min(_from.depth, _to.depth)
    for (d in minDepth downTo 0) {
        val start = _from.start(d)
        if (start < _from.pos - (_from.depth - d) ||
            _to.end(d) > _to.pos + (_to.depth - d) ||
            _from.node(d).type.spec.isolating == true ||
            _to.node(d).type.spec.isolating == true
        ) {
            break
        }
        if (start == _to.start(d) ||
            (
                    d == _from.depth && d == _to.depth && _from.parent.inlineContent && _to.parent.inlineContent &&
                            d != 0 && _to.start(d - 1) == start - 1
                    )
        ) {
            result.add(d)
        }
    }
    return result.toList()
}

fun ResolvedPosRange.coveredDepths() = coveredDepths(this.first,second)
